package com.gm.census.validation;

import java.lang.reflect.Field;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

import com.gm.census.annotations.validation.OneOf;

public class OneOfValidator implements ConstraintValidator<OneOf, Object> {

	private String[] properties;

	@Override
	public void initialize(OneOf oneOf) {
		this.properties = oneOf.propeties();
	}

	@Override
	public boolean isValid(Object value, ConstraintValidatorContext context) {
		Class<?> c = value.getClass();
		try {
			Boolean empty = true;
			for (String p : properties) {
				Field f = c.getDeclaredField(p);
				if (!f.isAccessible())
					f.setAccessible(true);
				Object o = f.get(value);
				if (o instanceof String) {
					empty &= (o == null || ((String) o).isEmpty());
				} else {
					empty &= o == null;
				}
				if (!empty) {
					break;
				}
			}
			return !empty;
		} catch (NoSuchFieldException e) {
			return false;
		} catch (IllegalArgumentException e) {
			return false;
		} catch (IllegalAccessException e) {
			return false;
		}
	}

}
